<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible="visible"
    @close="$emit('update:visible', false)"
  >
    <el-row type="flex" justify="center">
      <div class="upload-excel">
        <!-- 文件域 -->
        <input
          ref="excel-upload-input"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="handleUpload"
        >
        <div class="drop">
          <i class="el-icon-upload" />
          <el-button type="text" @click="handleDownloadTemplate">下载导入模板</el-button>
          <span>将文件拖到此处或
            <el-button type="text" @click="hadldeOpenFile">点击上传</el-button>
          </span>
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="end">
      <!-- update:props属性名，值直接修改 .sync修饰符的属性值 -->
      <el-button
        size="mini"
        type="primary"
        @click="$emit('update:visible', false)"
      >取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>

import { getExcelTemplateAPI, postEmpBatchAPI } from '@/api/employee'
import fileSaver from 'file-saver'
export default {
  props: {
    visible: Boolean
  },
  methods: {
    // 打开文件选择器
    hadldeOpenFile() {
      // 获取文件域DOM -> 调用click()方法
      this.$refs['excel-upload-input'].click()
    },
    // 上传Excel
    async handleUpload(e) {
      try {
       // 获取选中的Excel文件对象
        const { files } = e.target
        // 判断文件是否有值
        if (!files.length) return
        // 准备FormData类型参数
        const formData = new FormData()
        formData.append('file', files[0])
        // 调接口(把Excel中的多个员工一并存入数据库)
        await postEmpBatchAPI(formData)
        // 子传父(关闭弹框)
        this.$emit('update:visible', false)
        // 子传父(重新获取员工列表）
        this.$emit('success')
        // 提示
        this.$message.success('批量新增员工成功')
        // eslint-disable-next-line no-empty
      } catch (err) {

      } finally {
        // 清空文件选择器
        // eslint-disable-next-line require-atomic-updates
        e.target.value = ''
      }
    },
    // 下载导入模版
    async handleDownloadTemplate() {
      // 发请求获取流数据
      const blob = await getExcelTemplateAPI()
      // 流数据写入文件
      fileSaver.saveAs(blob, '上传员工Excel模版.xlsx')
    }
  }
}
</script>

<style scoped lang="scss">
    .upload-excel {
      display: flex;
      justify-content: center;
      margin: 20px;
      width: 360px;
      height: 180px;
      align-items: center;
      color: #697086;
      .excel-upload-input {
        display: none;
        z-index: -9999;
      }
      .btn-upload,
      .drop {
        border: 1px dashed #dcdfe6;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 160px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .drop {
        line-height: 40px;
        color: #bbb;
        i {
          font-size: 60px;
          display: block;
          color: #c0c4cc;
        }
      }
    }
</style>
